package unauth_controller

import (
	"gvb_service/common"
	"gvb_service/database"
	"gvb_service/model"
	user_service "gvb_service/service/user"
	"gvb_service/util"

	"github.com/gin-gonic/gin"
)

func UserRegister(c *gin.Context) {
	user := &model.User{}
	if err := c.ShouldBindJSON(user); err != nil {
		common.Fail(c, nil, "参数错误")
		return
	}
	result := user_service.CreateUser(user)
	if !result {
		common.Fail(c, nil, "添加失败")
		return
	}
	common.Success(c, nil, "用户添加成功")
}

func UserLogin(c *gin.Context) {
	// 验证用户是否正确
	user := &model.User{}
	if err := c.ShouldBindJSON(user); err != nil {
		common.Fail(c, nil, "参数错误")
		return
	}
	if !user_service.UserLogin(user.Username, user.Password) {
		common.Fail(c, nil, "用户名或密码错误")
		return
	}
	// 生成token
	token, err := util.GenerateToken(user.Username)
	if err != nil {
		common.Fail(c, nil, "生成token失败")
		return
	}
	// 缓存token
	redisResult := database.SetKey(user.Username, token, 60*60)
	if !redisResult {
		common.Fail(c, nil, "缓存token失败")
		return
	}
	common.Success(c, gin.H{"token": token}, "登录成功")
}

func Ping(c *gin.Context) {
	common.Success(c, gin.H{"ping": "pong"}, "请求成功")
}
